<template>
    <div>
        <basic-layout title="预约拜访" :showAddBtn="false">
            <div class="columnBg">
                <van-form ref="form">
                    <van-field readonly clickable name="被访人" label="被访人" required :value="formData.interviewerName" placeholder="请选择被访人" :rules=rules.interviewerId>
                        <template #button>
                            <a @click="$refs.staffListRef.handleInit(formData.interviewerId)">选择</a>
                        </template>
                    </van-field>
                    <van-field readonly name="被访人单位" label="被访人单位" :value="formData.interviewerCorpName" />
                    <van-field readonly name="被访人部门" label="被访人部门" :value="formData.interviewerDeptPathname" />
                    <h5>访客信息</h5>
                    <van-field readonly name="姓名" label="姓名" required :value="formData.visitor" placeholder="姓名" />
                    <div class="photoRow">
                        <div class="left">
                            <p>照片</p>
                            <p>上传高清正面图，用于人脸识别</p>
                        </div>
                        <div class="right">
                            <uploadCom ref="uploadRef" :maxNumber="1" @uploadFileIds="uploadFileIds" accept=".jpg,.jpeg,.png" :defaultFiles="defaultFiles"></uploadCom>
                        </div>
                    </div>
                    <van-field name="手机号" label="手机号" maxlength="11" required v-model="formData.visitorPhone" placeholder="请输入手机号" :rules=rules.visitorPhone>
                        <template #button v-if="!formData.visitorPhone">
                            <a @click="setMyInfo()">去设置</a>
                        </template>
                    </van-field>
                    <van-field readonly name="身份证" label="身份证" required :value="formData.visitorCertNo" placeholder="身份证">
                        <template #button v-if="!formData.visitorCertNo">
                            <a @click="setMyInfo()">去设置</a>
                        </template>
                    </van-field>
                    <van-field readonly clickable name="拜访时间" is-link label="拜访时间" required :value="formData.visitTime" placeholder="请选择拜访时间" @click="showChooseTimeComp" :rules=rules.visitTime />
                    <van-field readonly clickable name="离开时间" is-link label="离开时间" required :value="formData.departureTime" placeholder="请选择离开时间" @click="showChooseTimeComp" :rules=rules.departureTime />
                    <van-field readonly name="拜访事由" label="拜访事由" required :value="formData.visitReason" placeholder="请选择拜访事由" :rules=rules.visitReason>
                        <template #input>
                            <van-tag v-for="(item, ind) in visitReasonList" :color="tagColor[ind] || '#4eb3e9'" :plain="item.value !== formData.visitReason" @click="onReasonConfirm(item)">{{item.name}}</van-tag>
                        </template>
                    </van-field>
                    <van-field readonly clickable :value="formData.plateNumber" name="车牌号" label="车牌号" maxlength="16" type="text" placeholder="请输入车牌号" @click="showChoosePlate = true" :rules="formData.plateNumber ? rules.plateNumber : null" />
                </van-form>
                <div class="followerBox">
                    <h5 @click="isFold = !isFold;">
                        随行人员信息（{{followerList.length}}人）
                        <p v-if="isFold">展开 <van-icon name="arrow-down" /></p>
                        <p v-else>折叠 <van-icon name="arrow-up" /></p>
                        <van-button size="mini" round type="info" icon="plus" :disabled="followerList.length >= 5" @click="handleAdd"></van-button>
                    </h5>
                    <div v-show="!isFold" class="list">
                        <div v-for="(val, ind) in followerList" :key=ind class="list-item">
                            <img :src="val.url || 'images/convaccess/people.svg'">
                            <div class="right">
                                <div>
                                    <label>姓名：</label>
                                    <p>{{val.follower || "-"}}{{val.followerSexName ? ('（' + val.followerSexName + '）') : ''}}</p>
                                </div>
                                <div>
                                    <label>手机号：</label>
                                    <p>{{val.followerPhone || "-"}}</p>
                                </div>
                                <div>
                                    <label>{{val.visitorCertTypeName}}：</label>
                                    <p>{{(val.visitorCertType === '1' ? $infoHiding.handleIdCard(val.visitorCertNo) : val.visitorCertNo) || "-"}}</p>
                                </div>
                                <div>
                                    <label>来访单位：</label>
                                    <p>{{val.visitorCorpName || "-"}}</p>
                                </div>
                            </div>
                            <van-button plain color="#ee0a24" @click="handleDelete(ind)">删除</van-button>
                        </div>
                        <van-empty v-if="!followerList.length" class="custom-image" :image="require('../../../../assets/images/empty.png')" description="暂无随行人员" />
                    </div>
                </div>
                <div class="agreementBox">
                    <van-checkbox v-model="confirmAgreement" shape="square" icon-size="13px"></van-checkbox>
                    已阅读并同意 <a>《隐私协议》</a><a>《安全告知》</a>
                </div>
                <van-button class="defaultBtn" @click="handleSubmit">提交</van-button>
            </div>
        </basic-layout>
        <!-- 随行人员信息 -->
        <van-popup v-model="showVanPopup" position="bottom" :close-on-click-overlay="false" :style="{'height': '66%'}">
            <div class="addFormBox">
                <p>随行人员信息<van-icon size="20" name="cross" @click="showVanPopup = false" /></p>
                <div>
                    <addForm ref="addFormRef" @sendForm="getAddFollower" @close="showVanPopup = false;"></addForm>
                </div>
            </div>
        </van-popup>
        <!-- 选择被访人 -->
        <staffList ref="staffListRef" @sendStaff="getStaffInfo"></staffList>
        <!-- 选择拜访时间 -->
        <van-popup v-model="showChooseTime" position="bottom" :style="{'height': '75%'}">
            <chooseDateTime title="拜访" ref="chooseDateTimeRef" @close="showChooseTime = false" @sendTime="getVisitTime" />
        </van-popup>
        <!-- 选择访客中心 -->
        <van-dialog v-model="showDialog" title="访客中心选择" :showConfirmButton="false">
            <ul class="centerListBox">
                <li v-for="item in centerList" :key="item.centerId" @click="changeCenter(item)">
                    {{item.centerName}}
                    <van-icon name="success" v-if="item.centerId === formData.centerId" />
                </li>
            </ul>
        </van-dialog>
        <!-- 车牌号 -->
        <vnp-keyboard v-model="formData.plateNumber" :show.sync="showChoosePlate"></vnp-keyboard>
        <fullLoading v-if="loading"></fullLoading>
    </div>
</template>

<script>
    import addForm from './addForm.vue';
    import staffList from './staffList.vue';
    import chooseDateTime from './chooseDateTime.vue';
    import vnpKeyboard from '@/components/vant-number-plate/vnp-keyboard';
    import { queryDic, queryFileList } from '@/api/common';
    import { viewUserInfo } from '@/api/platframe/mainFrame/mine';
    import { addVisitors, queryInterviewerByCorpIdList, getByCenterId, getPhotoByCertNo, getLimitByCertNo, getBlackListByCertNo } from '@/api/srvAssurance/convaccess/appointmentVisit';

    export default {
        components: { addForm, staffList, chooseDateTime, vnpKeyboard },
        data () {
            return {
                loading: false,
                showVanPopup: false,
                isFold: true,
                confirmAgreement: false,
                showChooseTime: false,
                showDialog: false,
                showChoosePlate: false,
                formData: {
                    centerId: '',
                    interviewerId: '', // 被访人
                    interviewerName: '',
                    interviewerCorpId: '', // 被访人单位
                    interviewerCorpName: '',
                    interviewerDeptPathname: '', // 被访人部门
                    visitor: '', // 访客姓名
                    visitorPhoto: '', // 照片
                    visitorPhone: '', // 手机号
                    visitorCertType: '1', // 证件类型：身份证
                    visitorCertNo: '', // 身份证
                    visitTime: '', // 拜访时间
                    departureTime: '', // 离开时间
                    visitTimeDateStr: '',
                    visitReason: '', // 拜访事由
                    plateNumber: '', // 车牌号
                },
                rules: {
                    interviewerId: [
                        { required: true, message: '请选择被访人', trigger: 'onChange' }
                    ],
                    visitorPhone: [
                        { required: true, message: '请输入手机号', trigger: 'onBlur' },
                        { pattern: this.$commonReg.phoneReg, message: this.$commonReg.phoneMsg, trigger: 'onBlur' }
                    ],
                    visitTime: [
                        { required: true, message: '请选择拜访时间', trigger: 'onChange' }
                    ],
                    departureTime: [
                        { required: true, message: '请选择离开时间', trigger: 'onChange' }
                    ],
                    visitReason: [
                        { required: true, message: '请选择拜访事由', trigger: 'onChange' }
                    ],
                    plateNumber: [
                        { required: true, message: '请输入车牌号', trigger: 'onChange' },
                        { pattern: /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5,6}$/, message: '请输入正确的车牌号', trigger: 'onChange' }
                    ]
                },
                followerList: [], // 随行人员列表
                visitReasonList: [], // 拜访事由
                tagColor: ['#4eb3e9', '#07c160', '#ff976a', '#7232dd'],
                defaultFiles: [],
                centerList: [],
                centerConfig: {
                    entourageNum: '', // 随行人员数量
                    isLimitNum: '', // 是否限制访问次数
                    limitFrequency: '', // 访问频率
                    limitNum: '', // 访问次数
                    advanceReservationDay: '', // 可提前预约天数
                    continuousReservationMaxday: '', // 连续预约最大天数
                    beginTime: '', // 起始时间
                    endTime: '', // 截止时间
                    week: ''
                },
                isBlackList: false
            };
        },
        created () {
            this.getMyInfoData();
            this.getDicData();
        },
        methods: {
            // 提交
            handleSubmit () {
                if (!this.formData.visitor || !this.formData.visitorCertNo || !this.formData.visitorPhone ) {
                    this.$Notify({ type: 'warning', message: '请先完善身份证、手机号信息！' });
                    return
                }
                this.$refs.form.validate().then(async () => {
                    await this.getBlackListByCertNoData();
                    if (this.isBlackList) {
                        return
                    }
                    let start = new Date(this.formData.visitTime);
                    let end = new Date(this.formData.departureTime);
                    if (start > end) {
                        this.$Notify({ type: 'warning', message: '拜访时间不能大于离开时间！' });
                        return
                    }
                    if (!this.confirmAgreement) {
                        this.$Notify({ type: 'warning', message: '请阅读并同意隐私协议和安全告知！' });
                        return
                    }
                    let formData = {
                        ...this.formData,
                        visitMethod: '01',
                        visitType: '02',
                        visitorsEntourageSaveList: this.followerList
                    }
                    formData.visitTime = new Date(this.formData.visitTime).getTime(); // 拜访时间
                    formData.departureTime = new Date(this.formData.departureTime).getTime(); // 离开时间
                    this.loading = true;
                    addVisitors(formData).then(res => {
                        this.loading = false;
                        if (res.code === 1000) {
                            this.$Dialog.confirm({
                                title: '提交成功！请耐心等待审核结果。',
                                cancelButtonText: '新建预约拜访',
                                confirmButtonText: '查看预约记录'
                            }).then(() => {
                                this.$router.push({ name: 'convaccess-accessRecord' });
                            }).catch(() => {
                                this.handleReset();
                            });
                        }
                    }).catch(() => {
                        this.loading = false;
                    })
                })
            },
            // 附件上传
            uploadFileIds (arr) {
                this.formData.visitorPhoto = arr.length ? arr[0] : '';
            },
            // 选择被访人
            getStaffInfo (item) {
                this.formData.interviewerId = item.staffId;
                this.formData.interviewerName = item.name;
                this.formData.interviewerCorpId = item.corpId || '';
                this.formData.interviewerCorpName = item.corpName || '';
                this.formData.interviewerDeptPathname = item.deptFullName || '';
                this.formData.centerId = '';
                this.changeCenterResetData();
                this.queryInterviewerByCorpIdListData(item.staffId);
            },
            // 查询被访人访客中心
            queryInterviewerByCorpIdListData (staffId) {
                this.centerList = [];
                queryInterviewerByCorpIdList(staffId).then(res => {
                    if (res.code === 1000 && res.data) {
                        this.centerList = res.data;
                        if (res.data.length === 1) {
                            this.changeCenter(res.data[0]);
                        } else if (res.data.length > 1) {
                            this.showDialog = true;
                        } else {
                            this.$Dialog.alert({
                                message: '该被访人未配置访客中心，暂时无法访问！',
                            }).then(() => {
                                this.formData.interviewerId = '';
                                this.formData.interviewerName = '';
                                this.formData.interviewerCorpId = '';
                                this.formData.interviewerCorpName = '';
                                this.formData.interviewerDeptPathname = '';
                            });
                        }
                    }
                })
            },
            // 切换访客中心
            changeCenter (item) {
                this.formData.centerId = item.centerId;
                setTimeout(() => {
                    this.showDialog = false;
                    this.changeCenterResetData();
                    this.getByCenterIdData(item.centerId);
                }, 300)
            },
            // 切换访客中心部分信息重置
            changeCenterResetData () {
                this.formData.visitTime = '';
                this.formData.departureTime = '';
                this.formData.visitTimeDateStr = '';
                if (this.defaultFiles.length && this.defaultFiles[0].fileCode === this.formData.fileCode) {
                    this.formData.fileCode = '';
                }
                this.defaultFiles = [];
                this.centerConfig = {
                    entourageNum: '', // 随行人员数量
                    isLimitNum: '', // 是否限制访问次数
                    limitFrequency: '', // 访问频率
                    limitNum: '', // 访问次数
                    advanceReservationDay: '', // 可提前预约天数
                    continuousReservationMaxday: '', // 连续预约最大天数
                    beginTime: '', // 起始时间
                    endTime: '', // 截止时间
                    week: ''
                }
                if (this.$refs.chooseDateTimeRef) {
                    this.$refs.chooseDateTimeRef.getCenterConfig(this.centerConfig);
                }
            },
            // 获取访客中心配置信息
            getByCenterIdData (centerId) {
                getByCenterId(centerId).then(res => {
                    if (res.code === 1000 && res.data) {
                        for (var key in this.centerConfig) {
                            this.centerConfig[key] = res.data[key] || '';
                        }
                        this.getLimitByCertNoData(centerId);
                        this.getBlackListByCertNoData(centerId);
                        this.getPhotoByCertNoData(centerId);
                    }
                })
            },
            // 获取已访问次数
            getLimitByCertNoData (centerId) {
                if (this.centerConfig.isLimitNum != '1') return;
                getLimitByCertNo(centerId, this.formData.visitorCertNo).then(res => {
                    if (res.code === 1000 && res.data) {
                        if (res.data >= this.centerConfig.limitNum) {
                            let limitFrequency = this.centerConfig.limitFrequency;
                            let message = '';
                            if (limitFrequency == '1') {
                                message = '本月您已达最高访问次数，请下月再来！';
                            } else if (limitFrequency == '3') {
                                message = '本年您已达最高访问次数，请明年再来！';
                            } else {
                                message = '今日您已达最高访问次数，请明日再来！';
                            }
                            if (this.centerList.length > 1) {
                                this.$Dialog.confirm({
                                    title: message,
                                    cancelButtonText: '切换访客中心',
                                    confirmButtonText: '确定'
                                }).then(() => {
                                    this.formData.interviewerId = '';
                                    this.formData.interviewerName = '';
                                    this.formData.interviewerCorpId = '';
                                    this.formData.interviewerCorpName = '';
                                    this.formData.interviewerDeptPathname = '';
                                    this.formData.centerId = '';
                                    this.changeCenterResetData();
                                }).catch(() => {
                                    this.showDialog = true;
                                });
                            } else {
                                this.$Dialog.alert({
                                    message,
                                }).then(() => {
                                    this.formData.interviewerId = '';
                                    this.formData.interviewerName = '';
                                    this.formData.interviewerCorpId = '';
                                    this.formData.interviewerCorpName = '';
                                    this.formData.interviewerDeptPathname = '';
                                    this.formData.centerId = '';
                                    this.changeCenterResetData();
                                });
                            }
                        }
                    }
                })
            },
            // 判断是否在黑名单获取黑名单
            async getBlackListByCertNoData (centerId) {
                this.isBlackList = false;
                if (!this.formData.visitorCertNo || !centerId) return;
                await getBlackListByCertNo(centerId, this.formData.visitorCertNo).then(res => {
                    if (res.code === 1000 && res.data) {
                        this.isBlackList = true;
                        if (this.centerList.length > 1) {
                            this.$Dialog.alert({
                                message: '您已被该访客中心拉入黑名单，请切换访客中心！',
                            }).then(() => {
                                this.showDialog = true;
                            })
                        } else {
                            this.$Dialog.alert({
                                message: '您已被访客中心拉入黑名单，无法访问！',
                            }).then(() => { })
                        }
                    }
                })
            },
            // 获取回显照片
            getPhotoByCertNoData (centerId) {
                getPhotoByCertNo(centerId, this.formData.visitorCertNo).then(res => {
                    if (res.code === 1000 && res.data) {
                        if (res.data.fileCode) {
                            this.formData.visitorPhoto = res.data.fileCode;
                            this.queryPhotoFileInfoData(res.data.fileCode)
                        }
                    }
                })
            },
            // 获取头像信息
            queryPhotoFileInfoData (filecode) {
                queryFileList([filecode]).then(res => {
                    if (res.code === 1000 && res.data && res.data.length) {
                        this.defaultFiles = res.data.slice(0, 1);
                    }
                })
            },
            // 选择拜访事由
            onReasonConfirm (item) {
                this.formData.visitReason = item.value;
            },
            // 选择拜访时间
            showChooseTimeComp () {
                this.showChooseTime = true;
                this.$nextTick(() => {
                    this.$refs.chooseDateTimeRef.getCenterConfig(this.centerConfig, this.formData.visitTime && this.formData.departureTime);
                })
            },
            getVisitTime (params) {
                this.formData.visitTime = params.visitTime;
                this.formData.departureTime = params.departureTime;
                this.formData.visitTimeDateStr = params.visitTimeDateStr;
            },
            // 添加随行人员
            handleAdd (e) {
                e.stopPropagation();
                if (this.centerConfig.entourageNum && this.followerList.length >= this.centerConfig.entourageNum) {
                    this.$Notify({ type: "warning", message: `最多可添加${this.centerConfig.entourageNum}位随行人员！` });
                    return;
                }
                this.showVanPopup = true;
                this.$nextTick(() => {
                    this.$refs.addFormRef.resetForm();
                })
            },
            // 获取添加的人员信息
            getAddFollower (item) {
                this.followerList.push(item);
                if (this.isFold) this.isFold = false;
            },
            // 删除
            handleDelete (index) {
                this.followerList.splice(index, 1);
            },
            // 重置
            handleReset () {
                this.isFold = true;
                this.isBlackList = false;
                this.confirmAgreement = false;
                for (var key in this.formData) {
                    if (key != 'visitorPhone' && key != 'visitor' && key != 'visitorCertNo' && key != 'visitorCertType') {
                        this.formData[key] = '';
                    }
                }
                for (var key in this.centerConfig) {
                    this.centerConfig[key] = res.data[key] || '';
                }
                this.followerList = []; // 随行人员列表
                this.defaultFiles = [];
                this.$refs.uploadRef.reset();
                setTimeout(() => {
                    this.$refs.form.resetValidation();
                })
            },
            // 获取个人信息
            getMyInfoData () {
                if (!this.$store.state.userInfo.user) return;
                let id = this.$store.state.userInfo.user;
                viewUserInfo({ staffId: id }).then(res => {
                    if (res && res.code === 1000 && res.data) {
                        if (res.data.name || res.data.idCard || res.data.mobile) {
                            this.formData.visitor = res.data.name || '';
                            this.formData.visitorCertNo = res.data.idCard || '';
                            this.formData.visitorPhone = res.data.mobile || '';
                        }
                    }
                })
            },
            // 设置个人信息
            setMyInfo () {
                this.$router.push({ name: 'setUp-index' });
            },
            // 拜访事由
            getDicData () {
                queryDic('SA_VISITORS_REASON').then(res => {
                    if (res.code === 1000 && res.data) {
                        this.visitReasonList = res.data;
                    }
                })
            }
        },
    };
</script>

<style scoped lang="less">
    .van-form {
        background: #fff;
        .photoRow {
            display: flex;
            align-items: center;
            padding: 8px 15px;
            box-sizing: border-box;
            justify-content: space-between;
            position: relative;
            .left {
                line-height: 25px;
                p:nth-of-type(2) {
                    color: #999;
                    font-size: 12px;
                }
            }
        }
        .photoRow::after {
            position: absolute;
            box-sizing: border-box;
            content: " ";
            pointer-events: none;
            right: 0.42667rem;
            bottom: 0;
            left: 0.42667rem;
            border-bottom: 0.02667rem solid #ebedf0;
            -webkit-transform: scaleY(0.5);
            transform: scaleY(0.5);
        }
        /deep/.van-field__button a {
            color: #4eb3e9;
            font-size: 13px;
        }
        .van-tag {
            margin-right: 10px;
            line-height: 22px;
            padding: 0 8px;
        }
    }
    h5 {
        background: #f1f1f2;
        font-size: 13px;
        line-height: 42px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
        font-weight: normal;
        color: #666;
        position: relative;
        /deep/.van-button--mini {
            padding: 0;
            width: 18px;
            height: 18px;
        }
        p {
            position: absolute;
            right: 45px;
        }
    }
    .followerBox {
        background: #fff;
        margin-top: 5px;
        h5 {
            background: #fff;
        }
        /deep/.van-empty {
            padding: 20px 0;
            .van-empty__image {
                width: 50px;
                height: 50px;
            }
        }
        .list-item {
            display: flex;
            padding: 10px;
            box-sizing: border-box;
            align-items: center;
            img {
                width: 60px;
                height: 60px;
                margin-right: 10px;
            }
            .right {
                flex: 1;
                overflow: hidden;
                div {
                    display: flex;
                    line-height: 22px;
                    align-items: center;
                    font-size: 12px;
                    label {
                        color: #999;
                    }
                    p {
                        flex: 1;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                }
            }
            .van-button {
                height: 25px;
                padding: 0 10px;
                font-size: 12px;
            }
        }
    }
    .addFormBox {
        position: relative;
        p {
            text-align: center;
            line-height: 45px;
            font-size: 14px;
            margin-bottom: 5px;
            border-bottom: 1px solid #eee;
            color: #666;
        }
        & > div {
            padding: 0 10px;
            box-sizing: border-box;
        }
        .van-icon {
            position: absolute;
            right: 10px;
            top: 10px;
        }
    }
    .agreementBox {
        display: flex;
        font-size: 11px;
        padding: 10px;
        box-sizing: border-box;
        .van-checkbox {
            margin-right: 5px;
        }
    }
    .van-dialog {
        /deep/.van-dialog__header {
            padding: 10px 0;
        }
        .centerListBox {
            height: 180px;
            padding: 0 15px;
            line-height: 32px;
            font-size: 14px;
            overflow: auto;
            box-sizing: border-box;
            margin-bottom: 10px;
            li {
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                position: relative;
                padding-right: 30px;
                box-sizing: border-box;
                .van-icon {
                    position: absolute;
                    font-size: 18px;
                    top: 5px;
                    right: 0;
                    color: #4eb3e9;
                }
            }
        }
    }
</style>